<template>
  <q-dialog v-model="dialogVisible" :persistent="persistent">
    <q-card style="min-width: 350px">
      <q-card-section>
        <div class="text-h6">{{ title }}</div>
      </q-card-section>

      <q-card-section class="q-pt-none">
        <component
          v-if="component"
          :is="component"
          v-bind="componentProps"
          @submit="onSubmit"
          @cancel="onCancel"
        />
      </q-card-section>

      <q-card-actions align="right">
        <template v-for="(btn, index) in buttons" :key="index">
          <q-btn
            :flat="btn.flat !== false"
            :color="btn.color || 'primary'"
            :label="btn.label"
            :icon="btn.icon"
            v-bind="btn.props || {}"
            @click="onButtonClick(btn)"
          />
        </template>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue'

defineProps({
  title: String,
  content: String,
  component: Object,
  componentProps: Object,
  persistent: {
    type: Boolean,
    default: true,
  },
  buttons: {
    type: Array,
    default: () => [
      {
        label: '取消',
        color: 'primary',
        flat: true,
        action: 'cancel',
      },
      {
        label: '确定',
        color: 'primary',
        flat: true,
        action: 'confirm',
      },
    ],
  },
})

const emit = defineEmits(['confirm', 'cancel', 'update:visible'])

const dialogVisible = ref(false)

const show = () => {
  dialogVisible.value = true
}

const hide = () => {
  dialogVisible.value = false
}

const onButtonClick = (btn) => {
  if (btn.action === 'confirm') {
    emit('confirm')
  } else if (btn.action === 'cancel') {
    emit('cancel')
  }
  if (btn.onClick) {
    btn.onClick()
  }
  if (btn.closeOnClick !== false) {
    hide()
  }
}

const onCancel = () => {
  emit('cancel')
  hide()
}

const onSubmit = (data) => {
  emit('confirm', data)
  hide()
}

defineExpose({
  show,
  hide,
})
</script>
